<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\PraySetting;
use think\facade\Db;

/**
 * @extends Service<PraySettingService>
 */
class PraySettingService extends Service
{
    public function list($page, $limit, $searchQuery = null)
    {

        $w = [];
        $w[] = ['is_delete', '=', 0];
        $map = PraySetting::where($w)->page($page, $limit)->order('day_num asc');
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    public function save($data, $id = null)
    {
        Db::startTrans();
        try {
            if (empty($id)) {
                PraySetting::create([
                    'day_num' => $data['day_num'],
                    'amount' => $data['amount']
                ]);
            } else {
                $info = PraySetting::where('id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save([
                    'day_num' => $data['day_num'],
                    'amount' => $data['amount']
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function info($id)
    {
        $info = PraySetting::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }

        return $info->toArray();
    }


    public function del($id)
    {
        $info = PraySetting::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->save(['is_delete' => 1]);
    }

}